<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

class UeditorController extends Controller
{
    public function index(Request $request)
    {
        $action = $request->input('action');
        switch ($action) {
            case 'config':
                return $this->config();
            case 'image':
                return $this->image();
            default:
                return response()->json(["state" => "权限不足"]);
        }
    }

    /**
     * 获取ueditor 配置
     */
    private function config()
    {
        return response()->json(Config::get('UeditorConfig.upload', []));
    }

    public function image()
    {
        $file = request()->file('upfile');
        if (!$file) {
            return response()->json(['state' => '未获取到文件']);
        }
        $extension = $file->getClientOriginalExtension();
        $filename = $file->getClientOriginalName();
        $oriName = $file->getClientOriginalName();
        $fileSize = $file->getSize();
        $filePath = $file->getPathname();
        //新的文件名称
        $newFileName = date('His') . rand(1000, 99999) . '.' . $extension;
        //新的目录名称
        $mkdirName = "ueditor/".date("ymd");
        //是否上传七牛
        $isUploadQiNiu = config::get("images.isUploadQiNiu");
        if(!$isUploadQiNiu){
            $url = $file->storeAs($mkdirName, $newFileName, 'uploads');
            if (!$url) {
                return response()->json(['state' => '图片上传失败']);
            }
            $url = "/uploads/" . $url;
        }else{
            $fileName = "uploads/".$mkdirName."/".$newFileName;
            //Log::info("图片上传七牛 filePath:" . $filePath.",filename:" . $fileName);
            $imageUpload = new UploadsController();
            $imageUpload->imageTuQiniu($filePath,$fileName);
            //获取七牛配置
            $qiNiuConfig = $imageUpload->qiniuConfig();
            $domainUrl = $qiNiuConfig['domainUrl'];
            $url = $domainUrl."/".$fileName;
        }
        $data = [
            'state' => 'SUCCESS', // 上传状态，SUCCESS 或 ERROR
            'url' => $url, // 返回 URL 地址
            'title' => $filename, // 返回文件名
            'original' => $oriName, // 原始文件名
            'type' => $extension, // 文件类型
            'size' => $fileSize // 文件大小（字节）
        ];
        return response()->json($data);
    }
}
